"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig")
const SystemErrException = require("../../exception/systemError");
const LogicErrException = require("../../exception/logicError");

class RoleService extends Service {

  async add(roleMenusObj) {
    try {
      const { ctx } = this;
      let { name, remark } = roleMenusObj
      // 判断新增角色名称是否已经存在
      let isSingle = await this.ctx.model.Organization.Role.findAll({
        where: {
          name
        }
      })

      if (isSingle.length != 0) {
        return {
          code: httpCode.LOGICERROR,
          message: "角色名称已存在！"
        }
      }
      await ctx.model.Organization.Role.create({
        name,
        remark
      });
      return {
        code: httpCode.SUCCESS,
        message: "角色添加成功"
      }
    } catch (error) {
      this.ctx.logger.info(error);
    }
  }

  async list(requestData) {
    try {
      const { ctx } = this;
      let { currentPage = 1, pageSize = 999 } = requestData;
      let { count, rows: roles } = await ctx.model.Organization.Role.findAndCountAll({
        order: [['update_date', 'asc']],
        offset: (Number(currentPage) - 1) * Number(pageSize),
        limit: Number(pageSize)
      });
      return {
        data: {
          data: roles,
          count
        },
        code: httpCode.SUCCESS,
        message: '角色查询成功！'
      }
    } catch (error) {
      throw new SystemErrException("角色查询异常：" + error);
    }
  }

  async update(requestData) {
    let transaction;
    try {
      const { ctx } = this;
      let { id, name, remark } = requestData;
      await ctx.model.Organization.Role.update({
        name, remark
      }, {
        where: { id }
      })
      return {
        code: httpCode.SUCCESS,
        message: '更新成功！'
      }
    } catch (error) {
      this.ctx.logger.error(error);
      await transaction.rollback();
    }
  }

  async delete(id) {
    let transaction;
    try {
      const { ctx } = this;
      await ctx.model.Organization.Role.destroy({
        where: { id }
      })
      return {
        code: httpCode.SUCCESS,
        message: '删除成功！'
      }
    } catch (error) {
      throw new SystemErrException("角色删除异常：" + error);
    }
  }

}

module.exports = RoleService;
